package com.pinjitsu.web;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pinjitsu.entity.Highscore;
import com.pinjitsu.service.HighscoreService;
import com.pinjitsu.service.RestClientService;

@Controller
public class HighscoreController {

    private HighscoreService highscoreService;
    private RestClientService restClientService;

    @RequestMapping( value = "/highscore/submit", method = RequestMethod.POST )
    public ResponseEntity<String> saveHighscore(@RequestParam( value = "h" ) Long highscore, @RequestParam(
                    value = "fid" ) Long facebookId, HttpServletRequest request) throws JSONException {

        Highscore entity = new Highscore();

        entity.setHighscore(highscore);
        entity.setFacebookId(facebookId);
        // TODO get the current facebook user id;
        // entity.setFacebookId(new JSONObject(restClientService.getMyProfile(accessToken)).getLong("id"));
        entity.setTimestamp(new Date());
        highscoreService.saveHighscore(entity);
        HttpHeaders responseHeaders = new HttpHeaders();
        return new ResponseEntity<String>("", responseHeaders, HttpStatus.OK);

    }

    @RequestMapping( value = "/highscore/list" )
    @ResponseBody
    public List<Highscore> listHighscore(HttpServletRequest request) {
        return highscoreService.getAllHighscores(0, 10);
    }

    @RequestMapping( value = "/highscore/{facebookId}" )
    @ResponseBody
    public Long friendHighscore(@PathVariable Long facebookId) {
        return highscoreService.getFriendHighscores(facebookId, 0, 1);
    }

    public HighscoreService getHighscoreService() {
        return highscoreService;
    }

    @Autowired
    public void setHighscoreService(HighscoreService highscoreService) {
        this.highscoreService = highscoreService;
    }

    public RestClientService getRestClientService() {
        return restClientService;
    }

    @Autowired
    public void setRestClientService(RestClientService restClientService) {
        this.restClientService = restClientService;
    }
}
